#include "WebsocketHandler.h"

#if defined(WIN32)
#define WIN32_LEAN_AND_MEAN
#include <windows.h>

#include <Winsock2.h>
#include <WS2tcpip.h>
#include <ws2bth.h>
#endif

#if defined(LINUX)
#include <unistd.h>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#endif

#include <stdio.h>
#include <assert.h>

#if defined(WIN32)
#define close  closesocket
#endif

#if defined(LINUX)
#define INVALID_SOCKET -1
#endif

WebsocketHandler::WebsocketHandler(int _socket)
		:buff_()
		,status_(WEBSOCKET_UNCONNECT)
        , m_socket_(_socket)
		, request_(new WebsocketRequest())
		, respond_(new WebsocketRespond())
{

	assert(request_ != NULL);
	assert(respond_ != NULL);

}
WebsocketHandler::~WebsocketHandler()
{
	if (request_)
	{
		delete request_;
		request_ = NULL;
	}

	if (respond_)
	{
		delete respond_;
		respond_ = NULL;
	}

}

void WebsocketHandler::disconnect()
{
	if (m_socket_ != INVALID_SOCKET)
	{
		close(m_socket_);
		m_socket_ = INVALID_SOCKET;
	}
}



int WebsocketHandler::process(int fd,int nread)
{
    printf("recv nread %d  %s\n", nread,buff_);
	if (status_ == WEBSOCKET_UNCONNECT){
		int ret = respond_->handshark(m_socket_,buff_, nread);
		status_ = WEBSOCKET_HANDSHARKED;
		return ret;
	}

    return request_->process(m_socket_,buff_,nread,0);
}
